from PySide2.QtWidgets import (QApplication, QWidget, QVBoxLayout,
                               QStackedWidget, QDesktopWidget)
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import Qt
from PySide2.QtGui import QIcon
import sys
import time
import pyperclip
from OCR_Capture import CaptureWidget


class MainWidget(QWidget):
    def __init__(self):
        super().__init__()

        # combobox里对应的语言名称
        self._lang_dic = {
            'English': 'eng',
            'Chinese-sim': 'chi_sim',
            'Japanese': 'jpn',
            'Korean': 'kor'
        }

        self.initUi()  # 初始化界面
        self.setDefaultSettings()  # 设置默认参数

    def initUi(self):
        #################### capturetool窗口的设置 ####################
        # 从文件加载ui
        self._captureToolWidget = QUiLoader().load('./ui/OCRCaptureWidget.ui')
        # self._captureToolWidget.setWindowFlag(Qt.FramelessWindowHint)

        # 设置占位符
        self._captureToolWidget.textBrowser.setPlaceholderText(
            '  Waiting for process...')

        #################### setting界面的设置 ####################
        self._settingWidget = QUiLoader().load('./ui/setting.ui')
        self._settingWidget.theme_comboBox.addItem('dark')
        self._settingWidget.theme_comboBox.addItem('light')
        self._settingWidget.lang_comboBox.addItem('English')
        self._settingWidget.lang_comboBox.addItem('Chinese-sim')
        self._settingWidget.lang_comboBox.addItem('Japanese')
        self._settingWidget.lang_comboBox.addItem('Korean')

        # 堆叠窗口
        self._stackWidget = QStackedWidget()
        self._stackWidget.addWidget(self._captureToolWidget)  # 添加第一个窗口（主窗口）
        self._stackWidget.addWidget(self._settingWidget)  # 添加第二个窗口

        # 主界面只放一个layout，作为QStackedWidget的容器
        self._layout = QVBoxLayout()
        self._layout.addWidget(self._stackWidget)
        self.setLayout(self._layout)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)  # 页面置于最上层
        self.setWindowTitle('OCR Capture Tool')

        # 窗口居中
        self.setGeometry(0, 0, 400, 800)
        self.setMinimumWidth(300)
        self.setMinimumHeight(600)
        screen = QDesktopWidget().screenGeometry()  # 调用screenGeometry函数获得屏幕的尺寸
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)  # 调用move移动到指定位置

        # 关联按钮点击信号和槽
        self._captureToolWidget.add_content_button.clicked.connect(
            self.handleNewRequest)
        self._captureToolWidget.copy_button.clicked.connect(
            self.copystr2clipboard)
        self._captureToolWidget.clear_button.clicked.connect(self.clearText)
        self._captureToolWidget.setting_button.clicked.connect(
            self.switch2settingPage)  # 跳转到setting页面
        self._settingWidget.prevPage_button.clicked.connect(
            self.switch2mainPage)  # 跳转到main页面
        self._settingWidget.theme_comboBox.currentTextChanged.connect(
            self.setThemeStyle)
        self._settingWidget.lang_comboBox.currentTextChanged.connect(
            self.setOCRLanguage)
        self._settingWidget.windowOnTop_checkbox.stateChanged.connect(
            self.changeWindowFlag)

    # 一些默认参数的设置
    def setDefaultSettings(self):
        self.setThemeStyle('dark')
        self._lang = 'chi_sim'
        self._settingWidget.windowOnTop_checkbox.setChecked(True)
        self._settingWidget.lang_comboBox.setCurrentIndex(1)

    # 处理新请求
    def handleNewRequest(self):
        if self.isVisible():
            self.setVisible(False)
        time.sleep(0.3)  # 不加延时太快的话可能来不及隐藏界面
        self._captureW = CaptureWidget(
            self._lang)  # 捕获窗口截图时创建CaptureWidget并覆盖整个屏幕
        self._captureW.show()

        # 收到信号后打印结果，关闭截图界面
        self._captureW.send_str_signal.connect(self.printResult)
        self._captureW.close_capture_signal.connect(self.close_capture_widget)

    # 打印结果
    def printResult(self, strFromImg):
        self._captureToolWidget.textBrowser.append(strFromImg)
        self.setVisible(True)

    # 复制文本到系统剪贴板
    def copystr2clipboard(self):
        pyperclip.copy(self._captureToolWidget.textBrowser.toPlainText())

    def clearText(self):
        self._captureToolWidget.textBrowser.clear()

    # 关闭截图界面
    def close_capture_widget(self):
        self._captureW.close()
        self.setVisible(True)

    # 页面跳转
    def switch2settingPage(self):
        self._stackWidget.setCurrentIndex(1)

    def switch2mainPage(self):
        self._stackWidget.setCurrentIndex(0)

    # 设置主题样式
    def setThemeStyle(self, type):
        if type == 'dark':
            # load qss
            with open('./stylesheet/darkstyle.qss', 'r') as f:
                style = f.read()
                self.setStyleSheet(style)

            # icons
            self._captureToolWidget.add_content_button.setIcon(
                QIcon('./icons/scan-wh.png'))
            self._captureToolWidget.copy_button.setIcon(
                QIcon('./icons/copy-wh.png'))
            self._captureToolWidget.clear_button.setIcon(
                QIcon('./icons/clear-wh.png'))
            self._captureToolWidget.setting_button.setIcon(
                QIcon('./icons/setting-wh.png'))
            self._settingWidget.prevPage_button.setIcon(
                QIcon('./icons/backup-wh.png'))
        elif type == 'light':
            # load qss
            with open('./stylesheet/lightstyle.qss', 'r') as f:
                style = f.read()
                self.setStyleSheet(style)

            # icons
            self._captureToolWidget.add_content_button.setIcon(
                QIcon('./icons/scan-b.png'))
            self._captureToolWidget.copy_button.setIcon(
                QIcon('./icons/copy-b.png'))
            self._captureToolWidget.clear_button.setIcon(
                QIcon('./icons/clear-b.png'))
            self._captureToolWidget.setting_button.setIcon(
                QIcon('./icons/setting-b.png'))
            self._settingWidget.prevPage_button.setIcon(
                QIcon('./icons/backup-b.png'))
        else:
            pass

    # 设置语言
    def setOCRLanguage(self, lang):
        self._lang = self._lang_dic[lang]

    # 设置窗口层次
    def changeWindowFlag(self, state):
        if state == Qt.Unchecked:
            self.setWindowFlag(Qt.WindowStaysOnTopHint, False)
            if not self.isVisible():  # 有时设置以后会自动隐藏窗口
                self.setVisible(True)
        elif state == Qt.Checked:
            self.setWindowFlag(Qt.WindowStaysOnTopHint, True)
            if not self.isVisible():  # 有时设置以后会自动隐藏窗口
                self.setVisible(True)
        else:
            pass
            

def main():
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('./icons/OCRCapture.png'))  # 加载icon
    w = MainWidget()
    w.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
